package com.mingserve.raw.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingserve.common.core.constant.RawConstants;
import com.mingserve.common.mqtt.utils.MqttUtils;
import com.mingserve.raw.domain.Device;
import com.mingserve.raw.mapper.DeviceMapper;
import com.mingserve.raw.service.IDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * IoT设备管理Service接口实现
 *
 * @author lvwshuai
 * @date 2024-02-02
 */
@RequiredArgsConstructor
@Service
public class DeviceServiceImpl implements IDeviceService
{
    private final DeviceMapper deviceMapper;
    private final MqttUtils mqttUtils;

    /**
     * 批量新增或更新传感器
     *
     * @param list 测点列表
     * @return 结果
     */
    @Override
    public Boolean batchDevice(List<Device> list) {
        deviceMapper.delete(new QueryWrapper<>());
        return deviceMapper.insertOrUpdateBatch(list);
    }

    /**
     * 查询传感器列表
     *
     * @return 结果
     */
    @Override
    public List<Device> queryList() {
        return deviceMapper.selectList();
    }

    /**
     * 查询传感器详情
     *
     * @param deviceCode
     * @return
     */
    @Override
    public Device getDeviceByCode(String deviceCode) {
        return deviceMapper.selectOne(new QueryWrapper<Device>().eq("device_code", deviceCode));
    }

    /**
     * 变更传感器采集配置
     *
     * @param device
     * @return
     */
    @Override
    public Boolean updateDevice(Device device) {
        boolean flag = false;
        JSONObject config = JSONObject.parseObject(device.getConfig());
        config.put("SensorID", device.getDeviceCode());
        if (!config.containsKey("Otaflag")) {
            flag = deviceMapper.insertOrUpdate(device);
            // TODO: 2024/2/19 改为工作机组统一下发
//            if (flag) {
//                // 下发传感器配置
//                mqttUtils.publish(RawConstants.MQTT_DAQ, "cfg/" + device.getDeviceCode(), JSON.toJSONString(config));
//            }
        } else {
            // 下发传感器配置
            mqttUtils.publish(RawConstants.MQTT_DAQ, "cfg/" + device.getDeviceCode(), JSON.toJSONString(config));
        }
        return flag;
    }
}
